package com.jwsoft.manager.core.integration.impl;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.core.helper.DictHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.SchoolDictEnum;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.EduSchool;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.common.vo.eduSchoolBb.EduSchoolBbVO;
import com.jwsoft.manager.common.vo.eduSchoolBb.EduSchoolBbKeyVO;
import com.jwsoft.manager.common.vo.eduSchoolBb.EduSchoolBbQueryVO;
import com.jwsoft.manager.core.integration.EduSchoolBbIntegration;
import com.jwsoft.manager.core.dao.service.EduSchoolBbService;
import com.jwsoft.manager.core.dao.model.EduSchoolBb;
/**
 * 可补报学校表业务实现类
 *
 * @author wangtao
 * @since 2022-12-19
 */
@ApiService(funcCode = "eduSchoolBb", title = "可补报学校表")
public class EduSchoolBbIntegrationImpl implements EduSchoolBbIntegration {

    @Autowired
    public EduSchoolBbService eduSchoolBbService;

    @Autowired
    public DictHelper dictHelper;

    @Autowired
    private EduSchoolService eduSchoolService;

    @Override
    @OpApi(funcCode = "eduSchoolBb0001", title = "可补报学校表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduSchoolBbVO> getList(EduSchoolBbQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }

        QueryWrapper<EduSchoolBb> queryWrapper = new QueryWrapper();
        queryWrapper.select("school_bb_id,year,school_id,school_name,school_category,ifnull(full_flag,'0')full_flag,area_code")
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), "school_id", vo.getSchoolId())
                .eq(vo.getYear() != null, "year", vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getSchoolCategory()), "school_category", vo.getSchoolCategory())
                .eq(StringUtils.isNotBlank(vo.getSchoolNature()), "school_nature", vo.getSchoolNature())
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), "school_id", vo.getSchoolId())
                .eq(StringUtils.isNotBlank(vo.getAreaCode()),"area_code",vo.getAreaCode())
                .like(StringUtils.isNotBlank(vo.getSchoolName()), "school_name", vo.getSchoolName());
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<EduSchoolBb> list = eduSchoolBbService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSchoolBb> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSchoolBbVO> resultList = Convert.toList(EduSchoolBbVO.class, pageInfo.getList());
        // 转义数据字典值
         dictHelper.valueToName(resultList, Arrays.asList(SchoolDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSchoolBb0002", title = "可补报学校表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduSchoolBbVO getById(EduSchoolBbKeyVO vo) {
        EduSchoolBb entity = eduSchoolBbService.getById(vo.getSchoolBbId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSchoolBbVO result = Convert.convert(EduSchoolBbVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduSchoolBb0003", title = "可补报学校表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSchoolBbVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduSchoolBb0004", title = "可补报学校表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSchoolBb0004",
            operationName = "可补报学校表新增",
            dataType = "schoolBbId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSchoolBbVO add(EduSchoolBbVO bbvo) {

        //保存前校验
      //  checkSave(vo);
        List<EduSchoolBbVO> bbvoList = bbvo.getList();
        if(CollectionUtils.isEmpty(bbvoList)){
            throw new AppException("请先选择可补报的学校");
        }
        String areaCode = "";
        for (EduSchoolBbVO vo : bbvoList) {
            if (vo.getYear() == null) {
                throw new AppException(vo.getSchoolName() + "的数据中年度为空，请补全后重试");
            }
            if (StringUtils.isBlank(vo.getSchoolId())) {
                throw new AppException("存在学校ID为空的数据，请检查后重试！");
            }
            QueryWrapper<EduSchoolBb> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduSchoolBb::getYear, vo.getYear())
                    .eq(EduSchoolBb::getSchoolId, vo.getSchoolId());
            EduSchoolBb eduSchoolBb = eduSchoolBbService.getOne(queryWrapper);
            if(StringUtils.isBlank(vo.getAreaCode())){
                vo.setAreaCode(SessionUtil.getAreaCode());
            }
            areaCode = vo.getAreaCode();
            if (eduSchoolBb != null) {
                throw new AppException(eduSchoolBb.getSchoolName() + "已存在，请勿重复提交该校！");
            }
            EduSchoolBb entity = Convert.convert(EduSchoolBb.class, vo);
            eduSchoolBbService.save(entity);
        }
        clearCacheAreaCode(areaCode);
        return bbvo;
    }

    @Override
    @OpApi(funcCode = "eduSchoolBb0005", title = "可补报学校表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduSchoolBb0005",
            operationName = "可补报学校表修改",
            dataType = "schoolBbId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void edit(EduSchoolBbVO vo) {
        if (ObjectUtils.isEmpty(vo.getSchoolBbId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        if (ObjectUtils.isEmpty(vo.getSchoolId())){
            throw new AppException("学校不能为空!");
        }
        if (ObjectUtils.isEmpty(vo.getSchoolId())){
            throw new AppException("是否报满即止不能为空！");
        }
        EduSchoolBb old = eduSchoolBbService.getById(vo.getSchoolBbId());
        if (old == null) {
            throw new AppException("修改的信息不存在!");
        }
        EduSchool school = eduSchoolService.getById(vo.getSchoolId());
        if (ObjectUtils.isEmpty(school)){
            throw new AppException("补报学校信息不存在!");
        }
        UpdateWrapper<EduSchoolBb> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(EduSchoolBb::getSchoolBbId,vo.getSchoolBbId())
                .set(EduSchoolBb::getSchoolId,vo.getSchoolId())
                .set(EduSchoolBb::getFullFlag,vo.getFullFlag())
                .set(EduSchoolBb::getSchoolName,school.getSchoolName())
                .set(EduSchoolBb::getSchoolNature,school.getSchoolNature())
                .set(EduSchoolBb::getSchoolCategory,school.getSchoolCategory())
                .set(EduSchoolBb::getUpdateName,SessionUtil.getOrgId())
                .set(EduSchoolBb::getUpdateTime,new Date());
        eduSchoolBbService.update(updateWrapper);
        clearCacheAreaCode(school.getAreaCode());
    }

    @Override
    @OpApi(funcCode = "eduSchoolBb0006", title = "可补报学校表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSchoolBb0006",
            operationName = "可补报学校表删除",
            dataType = "schoolBbId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSchoolBbKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getSchoolBbId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSchoolBb entity = eduSchoolBbService.getById(vo.getSchoolBbId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSchoolBbService.removeById(vo.getSchoolBbId());
        clearCacheAreaCode(entity.getAreaCode());
    }

    @Override
    @OpApi(funcCode = "eduSchoolBb0007", title = "查询未补报公办学校列表", funcType = FuncTypeEnum.query)
    public PageInfo<EduSchoolVO> getSchoolBbList(EduSchoolBbQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        if (vo.getYear() == null) {
            throw new AppException("年度不能为空！");
        }

        List<EduSchoolVO> list = eduSchoolBbService.getSchoolBbList(vo);

        PageInfo<EduSchoolVO> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSchoolVO> resultList = Convert.toList(EduSchoolVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(SchoolDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    private void clearCacheAreaCode(String areaCode) {
        if (StringUtils.isNotBlank(areaCode)) {
            Cache cache = JetCacheUtils.create(EduCache.EDU_SCHOOL_areaCode, CacheType.BOTH);
            if (cache != null) {
                cache.remove(areaCode);
            }
        }
    }
}
